package controllers

import (
	"aticles/models"
	beego "github.com/beego/beego/v2/server/web"
	"math"
)

type GoodController struct {
	beego.Controller
}

func (c *GoodController) List() {
	page, _ := c.GetInt("page", 1)
	var count int64
	models.DB.Model(&models.Goods{}).Count(&count)
	size := 5
	sum := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size
	up := page - 1
	if up <= 1 {
		up = 1
	}
	down := page - 1
	if down > sum {
		down = sum
	}
	var allgood []models.Goods
	err := models.DB.Offset(offset).Limit(size).Find(&allgood).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
			"data": nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code":  200,
			"msg":   "查询成功",
			"data":  allgood,
			"page":  page,
			"size":  size,
			"count": count,
		}
		c.ServeJSON()
	}
}

func (c *GoodController) Add() {
	title := c.GetString("title")
	img := c.GetString("img")
	fl := c.GetString("fl")
	publish := c.GetString("publish")
	comment := c.GetString("comment")
	modify := c.GetString("modify")
	allgood := models.Goods{
		Title:   title,
		Img:     img,
		Fl:      fl,
		Publish: publish,
		Comment: comment,
		Modify:  modify,
	}
	err := models.DB.Create(&allgood).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
		}
		c.ServeJSON()
	}
}
